<?php
namespace app\api\controller;

use \think\Db;
class Apilogin extends Base
{
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 账号密码注册   2 重置密码
     * types       传1  图形验证
     * yzm         图形验证码
     */
    public function getPhoneCode()
    {
//        return json(['status' => 0, 'msg' => '系统升级中']);
        $params = input('');
        
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && isset($params['type']) && $params['type'] == 1) { // 注册
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { // 重置密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        
        // 图形验证码
        if(isset($params['types']) && $params['types'] == 1){
            $yzm  = input('yzm');
            $yzm_data = Db::table('up_phonecode')->where('phone',$params['phone'])->find();
            if($yzm_data['yzm'] != $yzm){
                return json(['status' => 0, 'msg' => '图形验证码错误']);
            }
            if($yzm_data['yzm_status'] != 1){
                return json(['status' => 0, 'msg' => '此图形验证码已使用，请重新获取']);
            }
            Db::table('up_phonecode')->where('phone',$params['phone'])->update(['yzm_status' => 2]);
        }
        $code_type = Db::table('up_about')->where('id', 2)->value('content');
        if($code_type == 1){
            $code = GetRandCode(); // 6位数验证码
        }else{
            $code = 111111;
        }
        $sendres = alisms($params['phone'], $code); // 发送验证码
        if($sendres['Code'] != 'OK') { // 发送不成功
            return json(['status' => 0, 'msg' => $sendres['Message']]);
        } else {
            $data = [
                'phone' => $params['phone'], // 发送的手机号
                'code' => $code, // 验证码
                'time' => time(), // 验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s') // 日期格式
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 图形验证码
     * phone   手机号
     */
    public function pictureyzm(){
        $phone = input('phone');
        header("content-type:image/png");
        $validateLength=4;
        $strToDraw="";
        $chars=[
            "1","2","3","4",
            "5","6","7","8","9",
            "a","b","c","d","e","f","g",
            "h","j","k","m","n",
            "p","q","r","s","t",
            "u","v","w","x","y","z",
            "A","B","C","D","E","F","G",
            "H","J","K","L","M","N",
            "P","Q","R","S","T",
            "U","V","W","X","Y","Z"
        ];
        $imgW=80;
        $imgH=25;
        $imgRes=imagecreate($imgW,$imgH);
        $imgColor=imagecolorallocate($imgRes,255,255,100);
        $color=imagecolorallocate($imgRes,0,0,0);
        for($i=0;$i<$validateLength;$i++){
            $rand=rand(0,9);
            $strToDraw=$strToDraw.$chars[$rand];
        }
        imagestring($imgRes,5,20,5,$strToDraw,$color);
        for($i=0;$i<100;$i++){
            imagesetpixel($imgRes,rand(0,$imgW),rand(0,$imgH),$color);
        }
        $where['phone'] = $phone;
        $res= Db::table('up_phonecode')->where($where)->find();
        if($res['id']!=''){ // 不等于空的时候
            $data['yzm'] = $strToDraw;
            $data['yzm_status'] = 1;
            
            Db::table('up_phonecode')->where($where)->update($data);
        }else{ // 等于空空
            $data['yzm'] = $strToDraw;
            $data['phone'] = $phone;
            Db::table('up_phonecode')->insert($data);
        }
        imagepng($imgRes);
        imagedestroy($imgRes);exit;
    }
    
    /**
     * 注册
     * @return string|\think\response\Json
     * phone     手机号
     * code      验证码
     * pwd       密码
     * invite_other   邀请我的人的邀请码
     */
    public  function register(){
//        return json(['status' => 0, 'msg' => '系统升级中']);
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $pwd = input('pwd');
        
        if(empty($phone)) return json(['status' => 0, 'msg' => '请填写手机号']);
        if(empty($code)) return json(['status' => 0, 'msg' => '请填写验证码']);
        if(empty($pwd)) return json(['status' => 0, 'msg' => '请填写密码']);
        
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json(['status' => 0, 'msg' => '请填写正确的手机号']);
        }
        
        $username = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(!empty($username)){
            return json(['status' => 0, 'msg' => '该手机号已注册']);
        }
    
        // 验证码
        $yzm = Db::table('up_phonecode')->where('phone', $phone)->order('time desc')->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 5分钟超时
        $now = time();
        if($now - $yzm['time'] >= 301) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $inivte_code = $this->getRandChar(8);
        $data = [
            'user_phone' => $phone,
            'user_password' => md5($pwd),
            'user_password_see' => $pwd,
            'user_time' => date('Y-m-d H:i:s'),
            'user_update_time' => date('Y-m-d H:i:s'),
            'user_invite' => $inivte_code,
            'user_invite_qrcode' => $this->getQrcode($inivte_code),
            'user_token' => $token,
            'user_last_login' => date('Y-m-d H:i:s')
        ];
        
        $id = Db::name('u_user')->insertGetId($data);
        if($id){
            $user = Db::table('up_u_user')->where('user_id', $id)->find();
            // todo:融云
            $rytoken = $this->rongyun($user['user_id'],'who',$user['user_image']);
            if($rytoken['code'] != 200){
                return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
            }
            $user['rytoken'] = $rytoken['token'];
            Db::table('up_phonecode')->where('phone',$phone)->update(['status' => 1]);
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 0, 'msg' => '生成数据失败,请刷新重试']);
        }
    }
    
    /**
     * 更新用户信息
     * @return \think\response\Json
     * user_image           用户头像
     * user_username        昵称
     * user_real_name       真实姓名
     * user_code            身份证
     * user_gender          性别   1 男   2 女
     * user_shop_name       店铺名称
     * user_bank_username   银行开户用户名
     * user_bank_name       开户银行
     * user_bankcard_code   银行卡
     * user_sheng           用户省
     * user_shi             用户市
     * user_qu              用户区
     * user_address         详细地址
     * user_id              用户ID
     * user_phone           手机号
     */
    public function updateUser(){
        $user_image = input('user_image');
        $user_username = input('user_username');
        $user_real_name = input('user_real_name');
        $user_gender = input('user_gender'); // 1 男   2 女
        $user_shop_name = input('user_shop_name');
        $user_phone = input('user_phone');
        $user_bank_username = input('user_bank_username') ? input('user_bank_username') : '';
        $user_bank_name = input('user_bank_name') ? input('user_bank_name') : '';
        $user_bankcard_code = input('user_bankcard_code') ? input('user_bankcard_code') : '';
        $user_sheng = input('user_sheng');
        $user_shi = input('user_shi');
        $user_qu = input('user_qu');
        $user_address = input('user_address');
        $user_id = input('user_id');
        $param = input();

        // 身份证认证
        $user_code = '';
        if(isset($param['user_code']) && $param['user_code'] != ''){
            $user_code = $param['user_code'];
            $check = $this->checkIdCard($user_real_name, $user_code);
            if($check['status'] == 0){
                return json($check);
            }
        }

        $sheng_name = Db::table('up_area')->where('district_id', $user_sheng)->value('district');
        $shi_name = Db::table('up_area')->where('district_id', $user_shi)->value('district');
        $qu_name = Db::table('up_area')->where('district_id', $user_qu)->value('district');
        // 用户信息
        $update = [
            'user_image' => $user_image,
            'user_username' => $user_username,
            'user_real_name' => $user_real_name,
            'user_gender' => $user_gender,
            'user_sheng' => $user_sheng,
            'user_shi' => $user_shi,
            'user_qu' => $user_qu,
            'user_area_str' => $sheng_name . $shi_name . $qu_name,
            'user_address' => $user_address,
            'user_update_time' => date('Y-m-d H:i:s'),
            'user_is_perfect' => 2,
            'user_phone' => $user_phone,
            'user_code' => $user_code
        ];
        if(isset($user_shop_name) && $user_shop_name != '') $update['user_shop_name'] = $user_shop_name;
        if(isset($user_bank_username) && $user_bank_username != '') $update['user_bank_username'] = $user_bank_username;
        if(isset($user_bank_name) && $user_bank_name != '') $update['user_bank_name'] = $user_bank_name;
        if(isset($user_bankcard_code) && $user_bankcard_code != '') $update['user_bankcard_code'] = $user_bankcard_code;
        
        Db::startTrans();
        try{
            // 更新用户信息
            Db::table('up_u_user')->where('user_id', $user_id)->update($update);

            // 默认第一条收货地址
            $address = [
                'addr_user_id' => $user_id,
                'addr_user_name' => $user_real_name,
                'addr_user_phone' => $user_phone,
                'addr_sheng' => $user_sheng,
                'addr_shi' => $user_shi,
                'addr_qu' => $user_qu,
                'addr_address' => $user_address,
                'addr_is_default' => 2,
                'addr_time' => date('Y-m-d H:i:s'),
                'addr_from' => 1
            ];
            Db::table('up_user_address')->insert($address);
            
            Db::commit();
            $user = Db::table('up_u_user')->find($user_id);
            // todo:融云
            $rytoken = $this->rongyun($user['user_id'],'who',$user['user_image']);
            if($rytoken['code'] != 200){
                return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
            }
            $user['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $user]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 账号密码登录
     * @return \think\response\Json
     * phone    手机号
     * pwd      密码
     */
    public function passwordLogin(){
//        return json(['status' => 0, 'msg' => '系统升级中']);
        $phone = trim(input('phone'), ' ');
        $pwd = input('pwd');
        if($phone == '') return json(['status' => 0, 'msg' => '请填写手机号']);
        if($pwd == '') return json(['status' => 0, 'msg' => '请填写密码']);
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)) return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        
        $password = md5($pwd);
        if(!empty($user) && $password != $user['user_password']) return json(['status' => 0, 'msg' => '密码错误']);
        if($user['user_status'] == 2){
            return json(['status' => 0, 'msg' => '账号无法使用，请联系管理员']);
        }
        if($user['user_status'] == 3){
            return json(['status' => 0, 'msg' => '账号已删除']);
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_login'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        
        if(!$user['user_invite']){ // 为了补全没有邀请码
            $inivte_code = $this->getRandChar(8);
            $data['user_invite'] = $inivte_code;
            $data['user_invite_qrcode'] = $this->getQrcode($inivte_code);
        }
        
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            $rytoken = $this->rongyun($userInfo['user_id'],'who',$userInfo['user_image']);
            if($rytoken['code'] != 200){
                return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
            }
            $userInfo['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 忘记密码
     * @return \think\response\Json
     * phone       手机号
     * code        验证码
     * pwd         密码
     */
    public function forgetPwd(){
//        return json(['status' => 0, 'msg' => '系统升级中']);
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $pwd = input('pwd');
    
        if(empty($phone)) return json(['status' => 0, 'msg' => '请填写手机号']);
        if(empty($code)) return json(['status' => 0, 'msg' => '请填写验证码']);
        if(empty($pwd)) return json(['status' => 0, 'msg' => '请填写密码']);
    
        if(!preg_match("/^1[123456789]\d{9}$/", $phone)){
            return json(['status' => 0, 'msg' => '请填写正确的手机号']);
        }
        
        $user = Db::table('up_u_user')->where('user_phone',$phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '该手机号尚未注册']);
        }
        
        // 验证码
        $yzm = Db::table('up_phonecode')->where('phone', $phone)->order('time desc')->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 5分钟超时
        $now = time();
        if($now - $yzm['time'] >= 301) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        
        $update = [
            'user_password' => md5($pwd),
            'user_password_see' => $pwd,
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($res){
            Db::table('up_phonecode')->where('phone',$phone)->update(['status' => 1]);
            return json(['status' => 200, 'msg' => '重置成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 第三方登录第一步----验证token
     * @return \think\response\Json
     * third_type       第三方类型   1 微信   2 apple
     * third_token      第三方token
     */
    public function thirdLoginF(){
//        return json(['status' => 0, 'msg' => '系统升级中']);
        $third_type = input('third_type'); // 1 微信   2 apple
        $third_token = input('third_token');
        $field = $third_type == 1 ? 'user_wx_token' : 'user_apple_token';
        if(!$third_token) return json(['status' => 0, 'msg' => '请先完成授权']);

        $first = Db::table('up_u_user')->where($field, $third_token)->field('user_id, user_status, user_invite, user_invite_qrcode')->find();
        if($first){
            if($first['user_status'] == 2){
                return json(['status' => 0, 'msg' => '账号无法使用，请联系管理员']);
            }
            if($first['user_status'] == 3){
                return json(['status' => 0, 'msg' => '账号已删除']);
            }
            $token = md5(date('YmdHis') . rand(100000, 999999));
            $data = [
                'user_last_login' => date('Y-m-d H:i:s'),
                'user_token' => $token
            ];
            
            if(!$first['user_invite']){
                $inivte_code = $this->getRandChar(8);
                $data['user_invite'] = $inivte_code;
                $data['user_invite_qrcode'] = $this->getQrcode($inivte_code);
            }
            $res = Db::table('up_u_user')->where('user_id', $first['user_id'])->update($data);
            if($res){
                $user = Db::table('up_u_user')->where('user_id', $first['user_id'])->find();
                // todo:融云
                $rytoken = $this->rongyun($user['user_id'],'who',$user['user_image']);
                if($rytoken['code'] != 200){
                    return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
                }
                $user['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $user]);
            }else{
                return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            }
        }else{
            // 第一次使用该第三方登录，先去绑定手机号
            return json(['status' => 201, 'msg' => '第一次登录，先绑定手机号']);
        }
    }
    
    /**
     * 第三方登录第二步---绑定手机号
     * @return \think\response\Json
     * phone          手机号
     * code           验证码
     * third_type     第三方类型    1 微信   2 apple
     * third_token    第三方token
     * third_image    第三方头像
     * third_nickname 昵称
     */
    public function thirdLoginS(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $third_type = input('third_type'); // 第三方类型   1 微信   2 apple
        $third_token = input('third_token');
        $third_image = input('third_image');
        $third_nickname = input('third_nickname');
        $field = $third_type == 1 ? 'user_wx_token' : 'user_apple_token';
    
        if(!$phone) return json(['status' => 0, 'msg' => '请输入手机号']);
        if(!$code) return json(['status' => 0, 'msg' => '请填写验证码']);
    
        // 验证码
        $yzm = Db::table('up_phonecode')->where('phone', $phone)->order('time desc')->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 5分钟超时
        $now = time();
        if($now - $yzm['time'] > 300) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        
        $exist = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($exist){ // 手机号注册过
            if($exist['user_status'] == 2) return json(['status' => 0, 'msg' => '该手机号无法使用，请联系管理员']);
            if($exist['user_status'] == 3) return json(['status' => 0, 'msg' => '该账号已删除']);
            $token = md5(date('YmdHis') . rand(100000, 999999));
            
            $update = [
                'user_last_login' => date('Y-m-d H:i:s'),
                'user_token' => $token,
                $field => $third_token
            ];
            if($third_type == 1){
                $update['user_wx_nickname'] = $third_nickname;
                $update['user_wx_image'] = $third_image;
            }
            if(empty($exist['user_image'])) $update['user_image'] = $third_image;
            if(empty($exist['user_username'])) $update['user_username'] = $third_nickname;
            
            if(!$exist['user_invite']){
                $inivte_code = $this->getRandChar(8);
                $update['user_invite'] = $inivte_code;
                $update['user_invite_qrcode'] = $this->getQrcode($inivte_code);
            }
            
            $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
            if($res){
                $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $yzm['id'])->setField('status', 1);
                // todo:融云
                $rytoken = $this->rongyun($user['user_id'],'who',$user['user_image']);
                if($rytoken['code'] != 200){
                    return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
                }
                $user['rytoken'] = $rytoken['token'];
                return json(['status' => 200, 'msg' => $user]);
            }else{
                return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
            }
        }else{ // 没有注册过
            return json(['status' => 202, 'msg' => '去设置密码']);
        }
    }
    
    /**
     * 第三方登录第三部---输入密码
     * @return \think\response\Json
     * phone          手机号
     * pwd            密码
     * third_type     第三方类型   1 微信   2 apple
     * third_token    第三方token
     * third_image    头像
     * third_nickname 昵称
     * invite_other   邀请我的人的邀请码
     */
    public function thirdLoginT(){
        $phone = trim(input('phone'), ' ');
        $pwd = input('pwd');
        $third_type = input('third_type'); // 第三方类型   1 微信   2 apple
        $third_token = input('third_token');
        $third_image = input('third_image');
        $third_nickname = input('third_nickname');
        $field = $third_type == 1 ? 'user_wx_token' : 'user_apple_token';
        if(!$pwd) return json(['status' => 0, 'msg' => '请输入密码']);
    
        $inivte_code = $this->getRandChar(8);
        $qrcode = $this->getQrcode($inivte_code);
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data = [
            'user_phone' => $phone,
            'user_password' => md5($pwd),
            'user_password_see' => $pwd,
            'user_time' => date('Y-m-d H:i:s'),
            'user_update_time' => date('Y-m-d H:i:s'),
            'user_invite' => $inivte_code,
            'user_invite_qrcode' => $qrcode,
            $field => $third_token,
            'user_token' => $token,
            'user_last_login' => date('Y-m-d H:i:s')
        ];
        if($third_type == 1){
            $data['user_username'] = $third_nickname;
            $data['user_image'] = $third_image;
            $data['user_wx_nickname'] = $third_nickname;
            $data['user_wx_image'] = $third_image;
        }

        $res = Db::table('up_u_user')->insertGetId($data);
        if($res){
            $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
            // todo:融云
            $rytoken = $this->rongyun($user['user_id'],'who',$user['user_image']);
            if($rytoken['code'] != 200){
                return json(['status' => 0, 'msg' => $rytoken['errorMessage']]);
            }
            $user['rytoken'] = $rytoken['token'];
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 平台用户使用协议
     * @return \think\response\Json
     */
    public function userAgreement(){
        $content = Db::table('up_about')->where('id', 6)->value('content');
        return json(['status' => 200, 'msg' => $content]);
    }
    
    /**
     * 平台用户隐私政策
     * @return \think\response\Json
     */
    public function ys(){
        header("Access-Control-Allow-Origin: *");
        $content = Db::table('up_about')->where('id', 9)->value('content');
        return json(['status' => 200, 'msg' => $content]);
    }
    
    /**
     * 第三方登录是否显示   1 显示   2 隐藏
     * @return \think\response\Json
     */
    public function showThirdLogin(){
        $content = Db::table('up_about')->where('id', 10)->value('content');
        return json(['status' => 200, 'msg' => $content]);
    }
    
    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        $area = file_get_contents('static/area.json');
        $area2 = json_decode($area,true);
        return json_encode($area2);
    }
    
    /**
     * app分享下载
     * @return \think\response\Json
     * share_type     1 Android    2 IOS
     */
    public function shareApp(){
        $share_type = input('share_type'); // 1 Android   2 IOS
        if($share_type == 1){
//            $url = 'https://appstore.huawei.com/app/C104325687';
//            $url = 'https://appgallery.huawei.com/app/C104325687'; // 华为
            $url = 'https://sj.qq.com/appdetail/com.dji.cn'; // 应用宝
        }else{
            $url = 'https://apps.apple.com/cn/app/%E7%82%B9%E5%8D%B3%E4%B8%BD/id1568240203';
        }
        
        return json(['status' => 200, 'msg' => $url]);
    }
    
    
    
    
    
    
    
    
    

 

    
    

}